package com.xhy.documents_collection.service.task.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xhy.documents_collection.entity.PO.task.TaskRecord;
import com.xhy.documents_collection.mapper.task.TaskRecordMapper;
import com.xhy.documents_collection.service.task.TaskRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2022-11-14
 */
@Service
public class TaskRecordServiceImpl extends ServiceImpl<TaskRecordMapper, TaskRecord> implements TaskRecordService {

    @Override
    public TaskRecord get(String taskRecordId) {

        return getById(taskRecordId);
    }

    @Override
    public Integer findUid(Integer taskId, Integer inviteId){
        Integer taskRecordId = findTaskRecordId(taskId, inviteId);
        return getOne(new QueryWrapper<TaskRecord>().eq("id",taskRecordId).select("u_id")).getUId();
    }

    public Integer findTaskRecordId(Integer taskId,Integer uId){
        // 查出自己组队情况,如果自己为null,说明已经有队伍了
        TaskRecord taskRecord = getOne(new QueryWrapper<TaskRecord>()
                .eq("t_id", taskId)
                .eq("u_id", uId).select("group_user_id").select("id"));
        // 为null则说明有队伍了,从其他记录中找到记录
        if (ObjectUtils.isEmpty(taskRecord)){
            List<TaskRecord> groups = list(new QueryWrapper<TaskRecord>().eq("t_id", taskId).select("group_user_id","id"))
                    .stream()
                    .filter(t -> (t.getGroupUserId().split(",").length) > 1).collect(Collectors.toList());
            // 从已经拥有的队伍中找到自己id
            for (TaskRecord record : groups) {
                for (String s : record.getGroupUserId().split(",")) {
                    if (uId.toString().equals(s)){
                        return record.getId();
                    }
                }
            }
        }

        return taskRecord.getId();
    }
}
